package com.firewolf.wx.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.firewolf.wx.entities.Category;
import com.firewolf.wx.service.CategoryService;

/**
 * 分类页签控制器
 * 
 * @author liuxing
 *
 */
@Controller
@RequestMapping("/cate")
public class CategoryController {

	@Autowired
	private CategoryService categoryService;

	/**
	 * 获取分类信息
	 * 
	 * @return
	 */
	@RequestMapping("/cates")
	@ResponseBody
	public List<Category> cates(@RequestParam(value = "pid", required = false, defaultValue = "0") Integer pid) {
		return categoryService.cates(pid);
	}

	/**
	 * 去微信后台获取OpenId和session_key
	 * 
	 * @param appID
	 * @param secret
	 * @param jsCode
	 * @return
	 */
	@RequestMapping("/wxUserInfo")
	@ResponseBody
	public WxInfo test(String appID, String secret, String jsCode) {
		String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appID + "&secret=" + secret + "&js_code="
				+ jsCode + "&grant_type=authorization_code";
		CloseableHttpClient httpCilent = HttpClients.createDefault();
		HttpGet httpGet = new HttpGet(url);
		WxInfo wxinfo = new WxInfo();
		try {
			CloseableHttpResponse httpResponse = httpCilent.execute(httpGet);
			BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));

			String inputLine;
			StringBuffer response = new StringBuffer();

			while ((inputLine = reader.readLine()) != null) {
				response.append(inputLine);
			}
			reader.close();
			System.out.println(response);
			String resulut = response.toString();
			ObjectMapper m = new ObjectMapper();
			wxinfo = m.readValue(resulut, WxInfo.class);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				httpCilent.close();// 释放资源
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return wxinfo;
	}
}
